using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Publicuse.Appication;
using Publicuse.Application;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Interface.Extend;
using Publicuse.Util;
using Geekeradmin.Authorize;

namespace Geekeradmin.Controllers
{
  /// <summary>
  /// 数据字典管理模块
  /// </summary>
  [UserAuthorize("Admin")]
  public class DictionariesController : BaseController
  {
    public DictionariesController(
      IAutofaceInstance autoface,
      IMySqlSugarService mySqlSugar,
      IWebHostEnvironment webHost,
      IOptions<DBConnectionOption> options,
      IBaseServiceExt baseServiceExt
    )
      : base(autoface, mySqlSugar, webHost, options, baseServiceExt) { }

    /// <summary>
    /// 获取数据三级联动信息
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetTreeList"), AllowAnonymous]
    public async Task<JsonResult> GetTreeList()
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .GetTreeList();
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取数据字典详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("GetListb")]
    public async Task<JsonResult> GetDetail(int Id)
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .GetDetail(Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取数据字典信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpPost("GetList")]
    public async Task<JsonResult> GetList(Dictionaries query)
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .GeList(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 检查数据字典类型编码是否存在
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dCode"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("CheckCode"), AllowAnonymous]
    public async Task<JsonResult> CheckCode(
      string dTypeName,
      string dCode,
      string loginUserCode,
      string Id = ""
    )
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .CheckCode(dTypeName, dCode,loginUserCode, Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 检查数据字典类型名称是否存在
    /// </summary>
    /// <param name="dName"></param>
    /// <param name="dTypeName"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("CheckName"), AllowAnonymous]
    public async Task<JsonResult> CheckName(
      string dName,
      string dTypeName,
      string loginUserCode,
      string Id = ""
    )
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .CheckName(dTypeName, dName, loginUserCode, Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 根据数据字典类型获取列表信息
    /// </summary>
    /// <param name="dTypeName"></param>
    /// <param name="dParentcode"></param>
    /// <returns></returns>
    [HttpGet("GetListc"), AllowAnonymous]
    public async Task<JsonResult> GetListc(string dTypeName, string dParentcode)
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .GetListc(dTypeName, dParentcode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取所有数据字典信息
    /// </summary>
    /// <returns></returns>
    [HttpGet("GetListd"), AllowAnonymous]
    public async Task<JsonResult> GetListd()
    {
      CommonResult result = await DictionariesApplication.GetApplication(this.container).GetListd();
      return new JsonResult(result);
    }

    /// <summary>
    /// 新增修改数据字典信息
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    [HttpPost("AddOrUpdate")]
    public async Task<JsonResult> AddOrUpdate(Dictionaries info)
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .AddOrUpdate(info);
      return new JsonResult(result);
    }

    /// <summary>
    /// 删除数据字典信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    [HttpGet("Delete")]
    public async Task<JsonResult> Delete(string Id, string loginUserCode, string type = "-9")
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .Delete(Id, loginUserCode, type);
      return new JsonResult(result);
    }

    /// <summary>
    /// 还原数据字典删除信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    [HttpGet("Reduction"), AllowAnonymous]
    public async Task<JsonResult> Reduction(string Id, string loginUserCode)
    {
      CommonResult result = await DictionariesApplication
        .GetApplication(this.container)
        .Reduction(Id, loginUserCode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 导出数据信息
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("ExportData")]
    public async Task<IActionResult> ExportData([FromQuery] Dictionaries query)
    {
      return await Task.Factory.StartNew<IActionResult>(() =>
      {
        MemoryStream ms = new MemoryStream();
        var exportname = "数据字典信息统计";
        var filepath = "\\template\\report\\dictionaries.xls";
        var tableName = TableAtributeUtil.GetTable<Dictionaries>();
        tableName =
          $"(select a.*,b.dName as dParentName from {tableName} a left join {tableName} b on a.dParentcode=b.Id group by a.Id) as urp";
        string sql = query.GetQueryString<Dictionaries>(null);
        DictionariesQuery dictionariesQuery = new DictionariesQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = "Id",
          sortType = "desc",
          files = "*",
          pageIndex = query.pageIndex,
          pageSize = 100000,
        };

        long total = 0;
        List<Dictionaries> list = new List<Dictionaries>();
        this.mySqlSugar.GetList<Dictionaries>(dictionariesQuery, out var msg, out list, out total);

        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          string webRootPath = webHost.WebRootPath;
          string fileName = webRootPath + filepath;
          ms = DictionariesExport.ExportData(fileName, exportname, list, out var msgb);
          if (string.IsNullOrEmpty(msg) && ms != null)
          {
            return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
          }
          else
          {
            return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
          }
        }
        else
        {
          return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
        }
      });
    }
  }
}
